/**
 * 

 */
package edu.vt.ece.rt.quorum.util;

import java.util.concurrent.atomic.AtomicBoolean;

import org.jgroups.Address;
import org.jgroups.Message;

import edu.vt.ece.rt.quorum.ClustersManager;
import edu.vt.ece.rt.quorum.messsages.types.MeasureCost;
import edu.vt.ece.rt.util.Logger.Logger;

/**
 * 
 * @author Sudhanshu
 *
 */
public class DistanceFinder implements Runnable {	
	Address dest;
	
	public DistanceFinder(Address d){
		dest = d;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		MeasureCost mc = new MeasureCost(true, dest);		
		ClustersManager.createEntry(dest);
		AtomicBoolean b = ClustersManager.distanceMap.get(dest).getWaitPoint();
		synchronized (b) {
			try {
				ClustersManager.getCluster(Names.base).send(new Message(dest, mc));
				Logger.debug("Waiting for response from " + dest);
				b.wait(ClustersManager.ClusterWaitTime);
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		Logger.debug("Got response from "+dest);
		if(!(b.get())){		//If unsuccessful set node not running
			ClustersManager.distanceMap.get(dest).node.setAccess(false);
		}		
	}

}
